//
//  H5ViewController.m
//  WashCar
//
//  Created by wangguodong on 14-8-14.
//  Copyright (c) 2014年 wuxian. All rights reserved.
//

#import "H5ViewController.h"

@interface H5ViewController () {
    
    //下拉视图
    EGORefreshTableHeaderView * _refreshHeaderView;
    //刷新标识，是否正在刷新过程中
    BOOL _reloading;
    BOOL _hasLoad;
    
}
@end

@implementation H5ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    if (_hasLoad==NO) {
        //        _contentWeb.frame = CGRectMake(0, self.navView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - self.navView.frame.size.height);
        [self configUI];
        _hasLoad = YES;
    }
}

- (void)configUI{
    _contentWeb = [[UIWebView alloc] initWithFrame:CGRectMake(0, self.navView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - self.navView.frame.size.height)];
    _contentWeb.delegate = self;
    _contentWeb.scrollView.delegate = self;
    _contentWeb.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_contentWeb];
    
    
    [WebViewJavascriptBridge enableLogging];
    
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:_contentWeb webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"ObjC received message from JS: %@", data);
        responseCallback(@"Response for message from ObjC");
    }];
    
    [_bridge registerHandler:@"frameShowLoading" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@"Response from frameShowLoading");
        [self frameShowLoading:data];
    }];
    
    [_bridge registerHandler:@"frameDismissLoading" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@"Response from frameDismissLoading");
        [self frameDismissLoading:data];
    }];
    
    [_bridge registerHandler:@"frameOpenUrl" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@"Response from frameOpenUrl");
        [self frameOpenUrl:data];
    }];
    
    if (_noRefresh==NO) {
        //初始化refreshView，添加到webview 的 scrollView子视图中
        if (_refreshHeaderView == nil) {
            _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, 0-_contentWeb.scrollView.bounds.size.height, _contentWeb.scrollView.frame.size.width, _contentWeb.scrollView.bounds.size.height)];
            _refreshHeaderView.delegate = self;
            [_contentWeb.scrollView addSubview:_refreshHeaderView];
        }
        [_refreshHeaderView refreshLastUpdatedDate];
        
        _contentWeb.scrollView.contentOffset = CGPointMake(0, -70);
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:_contentWeb.scrollView];
    }
    else {
        [self loadPage];
    }
}

- (void)loadPage {
    if ([_urlStr length]>0) {
        NSLog(@"_urlStr:%@",_urlStr);
        NSURL *url = [NSURL URLWithString:_urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        //        [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
        [_contentWeb loadRequest:request];
    }
}


- (void)frameShowLoading:(id)data {
    NSLog(@"data:%@",data);
}

- (void)frameDismissLoading:(id)data {
    NSLog(@"data:%@",data);
}

- (void)frameOpenUrl:(id)data {
    NSLog(@"data:%@",data);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[data objectForKey:@"url"]]];
}

- (void)backBtnAct:(id)sender {
    [self.contentWeb stopLoading];
    self.contentWeb.delegate = nil;
    
    self.urlStr = nil;
    self.bridge = nil;
    [super backBtnAct:sender];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"webViewDidStartLoad");
    if (_noRefresh) {
        [self frameShowLoading:nil];
    }
    _reloading = YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if (_noRefresh) {
        [self frameDismissLoading:nil];
    }
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_contentWeb.scrollView];
    [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.webkitTouchCallout='none';"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if (_noRefresh) {
        [self frameDismissLoading:nil];
    }
    NSLog(@"load page error:%@", [error description]);
    if ([error code] != NSURLErrorCancelled) {
//        if ([error code]!=101) {
//            XcWaitingAlertView *waitalert = [XcWaitingAlertView sharedInstance];
//            [waitalert presentWithText:@"亲，您的网络不给力哦～" withType:kAlertTypeWarnning];
//        }
    }
    
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_contentWeb.scrollView];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self loadPage];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
